<template>
  <div class="payment-records">
    <!-- 筛选表单 -->
    <el-form :inline="true" :model="filterForm" class="filter-form" size="small">
      <el-form-item label="充值时间">
        <el-date-picker
          v-model="filterForm.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 280px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="玩家ID">
        <el-input v-model="filterForm.uid" placeholder="请输入玩家ID" clearable type="number"></el-input>
      </el-form-item>
      <el-form-item label="渠道">
        <el-select v-model="filterForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
          <el-option
            v-for="item in channelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付渠道">
        <el-input v-model="filterForm.pay_channel" placeholder="请输入支付渠道" clearable></el-input>
      </el-form-item>
      <el-form-item label="三方订单编号">
        <el-input v-model="filterForm.third_order_id" placeholder="请输入三方订单编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="filterForm.order_id" placeholder="请输入订单编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="支付金额">
        <el-input v-model="filterForm.money" placeholder="请输入支付金额" clearable type="number"></el-input>
      </el-form-item>
      <el-form-item label="获得金币">
        <el-input v-model="filterForm.coin" placeholder="请输入获得金币" clearable type="number"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filterForm.status" placeholder="请选择状态" clearable style="width: 160px;">
          <el-option label="支付中" :value="1"></el-option>
          <el-option label="支付成功" :value="2"></el-option>
          <el-option label="发货成功" :value="3"></el-option>
          <el-option label="充值失败" :value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>支付记录</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportToCsv"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>

      <el-table
        :data="paymentRecords"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
      >
        <el-table-column prop="create_time" label="充值时间" width="150"></el-table-column>
        <el-table-column prop="uid" label="UUID" width="180"></el-table-column>
        <el-table-column prop="third_order_id" label="支付UUID" width="180"></el-table-column>
        <el-table-column prop="channel" label="用户渠道" width="150"></el-table-column>
        <el-table-column prop="order_id" label="订单号" width="220"></el-table-column>
        <el-table-column prop="channel" label="支付途径" width="120"></el-table-column>
        <el-table-column prop="money" label="支付金额" width="120"></el-table-column>
        <el-table-column prop="coin" label="充值金币" width="120"></el-table-column>
        <el-table-column prop="status" label="支付状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { payRecord } from '@/api/user'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'PaymentRecords',
  mixins: [channelMixin],
  data() {
    return {
      filterForm: {
        dateRange: [],
        uid: '',
        channel: null,
        pay_channel: '',
        third_order_id: '',
        order_id: '',
        money: '',
        coin: '',
        status: ''
      },
      paymentRecords: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      exportLoading: false
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          uid: this.filterForm.uid ? parseInt(this.filterForm.uid) : 0,
          channel: this.formatChannelParam(this.filterForm.channel),
          pay_channel: this.filterForm.pay_channel || '',
          third_order_id: this.filterForm.third_order_id || '',
          order_id: this.filterForm.order_id || '',
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : '',
          money: this.filterForm.money ? parseInt(this.filterForm.money) : 0,
          coin: this.filterForm.coin ? parseInt(this.filterForm.coin) : 0,
          status: this.filterForm.status || 0,
          page: this.currentPage,
          page_size: this.pageSize
        }
        
        const response = await payRecord(params)
        
        if (response.code === 0) {
          this.paymentRecords = response.data.records || []
          this.total = response.data.total_page * this.pageSize || 0
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取支付记录失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    getStatusType(status) {
      const statusMap = {
        1: 'warning', // 支付中
        2: 'success', // 支付成功
        3: 'success', // 发货成功
        4: 'danger'   // 充值失败
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        1: '支付中',
        2: '支付成功',
        3: '发货成功',
        4: '充值失败'
      }
      return statusMap[status] || '未知状态'
    },
    handleFilter() {
      this.currentPage = 1
      this.fetchData()
    },
    resetFilter() {
      this.filterForm = {
        dateRange: [],
        uid: '',
        channel: null,
        pay_channel: '',
        third_order_id: '',
        order_id: '',
        money: '',
        coin: '',
        status: ''
      }
      this.currentPage = 1
      this.fetchData()
    },
    async exportToCsv() {
      this.exportLoading = true
      
      try {
        // 构建CSV内容
        let csvContent = '充值时间,UUID,支付UUID,用户渠道,订单号,支付途径,支付金额,充值金币,支付状态\n'
        
        this.paymentRecords.forEach(row => {
          csvContent += `${row.create_time},${row.uid},${row.third_order_id},${row.channel},${row.order_id},${row.channel},${row.money},${row.coin},${this.getStatusText(row.status)}\n`
        })
        
        // 创建Blob对象并下载
        const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a')
        const url = URL.createObjectURL(blob)
        
        link.setAttribute('href', url)
        link.setAttribute('download', `支付记录_${new Date().toLocaleDateString()}.csv`)
        link.style.visibility = 'hidden'
        
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        this.$message.success('导出成功')
      } catch (error) {
        this.$message.error('导出失败：' + error.message)
      } finally {
        this.exportLoading = false
      }
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.payment-records {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-form {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 